package com.chuangshu.chuangshuteam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chuangshu.chuangshuteam.entity.TeamMember;
import com.chuangshu.chuangshuteam.mapper.TeamMemberMapper;
import com.chuangshu.chuangshuteam.service.AuthService;
import com.chuangshu.chuangshuteam.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private TeamMemberMapper teamMemberMapper;

    @Autowired
    private UsersService usersService;

    // 预定义角色常量
    private static final String ROLE_ADMIN = "admin";
    private static final String ROLE_LEADER = "leader";
    private static final String ROLE_MEMBER = "member";

    /**
     * 检查用户是否有指定权限
     * 未加入团队的用户只有基础权限
     */
    @Override
    public boolean hasPermission(Long userId, String permissionCode) {
        // 首先检查用户是否已加入团队
        if (!usersService.isUserInTeam(userId)) {
            // 未加入团队的用户只有基础权限
            return hasBasicPermission(permissionCode);
        }

        // 管理员拥有所有权限
        if (isAdmin(userId)) {
            return true;
        }

        TeamMember teamMember = getTeamMemberInfo(userId);
        if (teamMember == null) {
            return false;
        }

        // 根据角色判断权限
        String roleName = teamMember.getRole() != null ? teamMember.getRole().getName() : ROLE_MEMBER;

        switch (permissionCode) {
            case "user:delete":
            case "user:list":
            case "team:edit":
            case "recruitment:all":
                return ROLE_ADMIN.equals(roleName);
            case "recruitment:create":
            case "recruitment:manage":
                return ROLE_ADMIN.equals(roleName) ||
                        (ROLE_LEADER.equals(roleName) && hasDirectionPermission(userId, teamMember.getDirection()));
            default:
                return true; // 其他权限默认允许
        }
    }

    /**
     * 未加入团队的用户的基础权限
     */
    private boolean hasBasicPermission(String permissionCode) {
        // 定义未加入团队用户可以访问的权限
        List<String> basicPermissions = Arrays.asList(
                "user:profile",     // 查看个人资料
                "user:update",      // 更新个人资料
                "user:direction",   // 设置专业方向
                "public:read"       // 查看公开内容
        );

        return basicPermissions.contains(permissionCode);
    }

    /**
     * 检查用户是否有指定角色
     * 未加入团队的用户没有角色
     */
    @Override
    public boolean hasRole(Long userId, String roleName) {
        if (!usersService.isUserInTeam(userId)) {
            return false; // 未加入团队的用户没有角色
        }

        TeamMember teamMember = getTeamMemberInfo(userId);
        if (teamMember == null || teamMember.getRole() == null) {
            return false;
        }
        return roleName.equals(teamMember.getRole().getName());
    }

    /**
     * 检查用户是否是管理员
     */
    @Override
    public boolean isAdmin(Long userId) {
        return hasRole(userId, ROLE_ADMIN);
    }

    /**
     * 检查用户是否是方向负责人
     */
    @Override
    public boolean isDirectionLeader(Long userId, String direction) {
        if (!usersService.isUserInTeam(userId)) {
            return false; // 未加入团队的用户不能是方向负责人
        }

        TeamMember teamMember = getTeamMemberInfo(userId);
        if (teamMember == null || teamMember.getRole() == null) {
            return false;
        }

        return ROLE_LEADER.equals(teamMember.getRole().getName()) &&
                direction.equals(teamMember.getDirection());
    }

    /**
     * 检查用户是否有权限访问指定方向的数据
     */
    @Override
    public boolean hasDirectionPermission(Long userId, String direction) {
        if (!usersService.isUserInTeam(userId)) {
            return false; // 未加入团队的用户不能访问方向数据
        }

        TeamMember teamMember = getTeamMemberInfo(userId);
        if (teamMember == null) {
            return false;
        }

        // 管理员可以访问所有方向
        if (isAdmin(userId)) {
            return true;
        }

        // 方向负责人只能访问自己负责的方向
        if (isDirectionLeader(userId, teamMember.getDirection())) {
            return direction.equals(teamMember.getDirection());
        }

        // 普通成员只能访问自己所在的方向
        return direction.equals(teamMember.getDirection());
    }

    @Override
    public TeamMember getTeamMemberInfo(Long userId) {
        // 默认团队ID为1（单团队模式）
        Long teamId = 1L;

        LambdaQueryWrapper<TeamMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamMember::getUserId, userId)
                .eq(TeamMember::getTeamId, teamId);

        return teamMemberMapper.selectOne(queryWrapper);
    }

    @Override
    public List<String> getUserDirections(Long userId) {
        if (!usersService.isUserInTeam(userId)) {
            return Collections.emptyList(); // 未加入团队的用户没有方向
        }

        TeamMember teamMember = getTeamMemberInfo(userId);
        if (teamMember == null) {
            return Collections.emptyList();
        }

        // 管理员可以访问所有方向
        if (isAdmin(userId)) {
            return Arrays.asList("frontend", "backend", "ui", "cv", "pm", "embedded", "general");
        }

        // 其他用户只能访问自己所在的方向
        return Collections.singletonList(teamMember.getDirection());
    }

    /**
     * 检查用户是否已加入团队
     */
    @Override
    public boolean isUserInTeam(Long userId) {
        return usersService.isUserInTeam(userId);
    }

    @Override
    public boolean hasTeamManagementPermission(Long userId) {
        // 只有管理员有团队管理权限
        return isAdmin(userId);
    }
    @Override
    public List<String> getUserPermissions(Long userId) {
        if (isAdmin(userId)) {
            return List.of(
                    "user:delete", "user:list", "team:edit",
                    "recruitment:all", "team:invite:reset"
            );
        } else if (hasRole(userId, "leader")) {  // 直接调用当前类的hasRole方法
            return List.of("recruitment:create", "recruitment:manage");
        } else {
            return List.of();
        }
    }
}